/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.theme.passport.controller.app;


import com.theme.common.base.EmojiHandler;
import com.theme.common.base.PinYinUtils;
import com.theme.common.base.StringHandler;
import com.theme.common.mvc.exception.RRException;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.validator.ValidatorUtils;
import com.theme.common.mvc.view.R;
import com.theme.passport.annotation.Login;
import com.theme.passport.controller.app.utils.AppContextUtil;
import com.theme.passport.controller.oss.cloud.OSSFactory;
import com.theme.passport.entity.SysMessageEntity;
import com.theme.passport.entity.SysMessageUserEntity;
import com.theme.passport.entity.UserEntity;
import com.theme.passport.entity.constant.MessageTypeEnum;
import com.theme.passport.entity.constant.MessageUserTypeEnum;
import com.theme.passport.form.UserUpdateForm;
import com.theme.passport.service.SysMessageService;
import com.theme.passport.service.SysMessageUserService;
import com.theme.passport.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("app/user")
@Api("用户接口")
public class AppUserController {

    private static final Logger logger = LoggerFactory.getLogger(AppUserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private SysMessageService messageService;

    @Autowired
    private SysMessageUserService messageUserService;

    @GetMapping("notToken")
    @ApiOperation("忽略Token验证测试")
    public R notToken() {
        return R.ok().put("msg", "无需token也能访问。。。");
    }

    @Login
    @GetMapping("info")
    @ApiOperation("根据用户Id获取用户信息")
    public R userInfo() {
        UserEntity currentUser = AppContextUtil.getCurrentUser();
        logger.info("根据用户Id获取用户信息:[当前登录用户nickname:{},用户userId：{}]",currentUser.getNickname(),currentUser.getId());
        currentUser.setPassword(null);
        return R.ok().put("user", currentUser);
    }

    @Login
    @PostMapping("update")
    @ApiOperation("完善用户信息")
    public R update(@RequestBody UserUpdateForm updateForm) {
        //表单校验
        ValidatorUtils.validateEntity(updateForm);

        UserEntity currentUser = AppContextUtil.getCurrentUser();
        UserEntity user = userService.getById(currentUser.getId());
        if (user == null) {
            return R.error(1001, "用户不存在!");
        }
        if (StringHandler.isNotEmpty(updateForm.getMobile())) user.setMobile(updateForm.getMobile());
        if (StringHandler.isNotEmpty(updateForm.getEmail())) user.setEmail(updateForm.getEmail());
        if (StringHandler.isNotEmpty(updateForm.getGender())) user.setGender(updateForm.getGender());
        if (StringHandler.isNotEmpty(updateForm.getNickname())){
            String newNickname = EmojiHandler.filterEmoji(updateForm.getNickname());
            user.setUsername(PinYinUtils.getPingYin(newNickname));
            user.setNickname(newNickname);
        }
        userService.updateUserById(user);
        return R.ok();
    }

    @Login
    @PostMapping("updateInfo")
    @ApiOperation("修改用户昵称接口")
    public R updateInfo(@RequestParam("nickname") String nickname,
                        @RequestParam(value = "gender", required = false) Integer gender,
                        @RequestParam(value = "email", required = false) String email,
                        @RequestParam(value = "mobile", required = false) String mobile) {
        UserEntity currentUser = AppContextUtil.getCurrentUser();
        UserEntity user = userService.getById(currentUser.getId());
        if (user == null) {
            return R.error(1001, "用户不存在!");
        }
        String newNickname = EmojiHandler.filterEmoji(nickname);
        user.setUsername(PinYinUtils.getPingYin(newNickname));
        user.setNickname(newNickname);
        if (StringHandler.isNotEmpty(gender)) user.setGender(gender);
        if (StringHandler.isNotEmpty(mobile)) user.setMobile(mobile);
        if (StringHandler.isNotEmpty(email)) user.setEmail(email);
        userService.updateUserById(user);
        return R.ok();
    }

    @Login
    @PostMapping("updatePassword")
    @ApiOperation("修改用户密码接口")
    public R updatePassword(@RequestParam(value = "password") String password) {
        UserEntity currentUser = AppContextUtil.getCurrentUser();
        UserEntity user = userService.getById(currentUser.getId());
        if (user == null) {
            return R.error(1001, "用户不存在!");
        }
        user.setUpdateTime(new Date());
        user.setPassword(DigestUtils.sha256Hex(password));
        userService.updateUserById(user);
        return R.ok();
    }

    @Login
    @PostMapping("updateAavatar")
    @ApiOperation("修改用户头像")
    public R updateAavatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //上传文件
        try {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String url = OSSFactory.build(null).uploadSuffix(file.getBytes(), suffix);
            UserEntity currentUser = AppContextUtil.getCurrentUser();
            currentUser.setAvatar(url);
            userService.updateUserById(currentUser);
            Map<String,Object> result= new HashMap<>();
            result.put("avatar",url);
            return R.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    @GetMapping("sysNotice")
    @ApiOperation("获取系统公告")
    public R sysNotice() {
        int groupType = MessageUserTypeEnum.PORTAL.getValue();
        int type = MessageTypeEnum.SYSTEM_NOTICE.getValue();
        PageUtils page = messageService.querySysNotice(groupType, type);
        List<SysMessageEntity> list = (List<SysMessageEntity>) page.getList();
        SysMessageEntity userMessage = new SysMessageEntity();
        if (list != null && list.size() > 0) {
            userMessage = list.get(0);
        }
        return R.ok().put("message", userMessage);
    }


    @Login
    @GetMapping("notice")
    @ApiOperation("获取用户消息")
    public R notice(@RequestAttribute("userId") String userId) {
        int toType = MessageUserTypeEnum.PORTAL.getValue();
        int messageType = MessageTypeEnum.SYSTEM_NOTICE.getValue();
        PageUtils page = messageUserService.queryUserNotice(Long.valueOf(userId), toType, messageType);
        List<SysMessageUserEntity> list = (List<SysMessageUserEntity>) page.getList();
        SysMessageUserEntity userMessage = new SysMessageUserEntity();
        if (list != null && list.size() > 0) {
            userMessage = list.get(0);
        }
        SysMessageEntity message = messageService.getById(userMessage.getMessageId());
        userMessage.setTitle(message.getTitle());
        userMessage.setContent(message.getContent());
        return R.ok().put("userMessage", userMessage);
    }

}
